package main.users;

import main.SQL.MsSQLConnect;
import main.components.GradientPanel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class AddUserDialog {
    private JDialog dlg;
    private UsersTableModel usersTableModel;
    private JTextField inputLogin, inputName;
    private JComboBox roleList;

    public AddUserDialog(UsersTableModel usersTableModel) {
        this.usersTableModel = usersTableModel;
        initComponents();
    }

    private void initComponents() {
        dlg = new JDialog();
        dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dlg.setLayout(new GridBagLayout());
        dlg.setTitle("Add Factage User");
        dlg.setResizable(true);
        dlg.setType(java.awt.Window.Type.UTILITY);
        dlg.setModal(true);

        //region Инициализация шапки
        GradientPanel headerPanel = new GradientPanel(new GridBagLayout(), new Color(140, 250, 156), new Color(99, 176, 111));
        JLabel headerLabel = new JLabel("Добавить пользователя системы Factage");
        headerLabel.setFont(new Font("Segoe UI", 0, 18));
        headerLabel.setForeground(Color.WHITE);
        dlg.add(headerPanel, new GridBagConstraints(0, 0, 3, 1, 0.1, 0.1, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
        headerPanel.add(headerLabel, new GridBagConstraints(0, 0, 1, 1, 0.5, 0, GridBagConstraints.WEST, GridBagConstraints.WEST, new Insets(30, 56, 7, 56), 0, 0));
        //endregion

        dlg.add(new JLabel("Логин"), new GridBagConstraints(0, 1, 1, 1, 0, 0.1, GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(31, 56, 0, 0), 0, 0));
        dlg.add(new JLabel("Имя пользователя"), new GridBagConstraints(0, 2, 1, 1, 0, 0.1, GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(22, 56, 0, 0), 0, 0));
        dlg.add(new JLabel("Роль"), new GridBagConstraints(0, 3, 1, 1, 0, 0.1, GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(22, 56, 0, 0), 0, 0));

        inputLogin = new JTextField("Логин");
        inputLogin.setPreferredSize(new Dimension(180, 22));
        inputLogin.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent focusEvent) {
                inputLogin.setForeground(Color.black);
                if (inputLogin.getText().equals("Логин")){
                    inputLogin.setText("");
                }
            }
            @Override
            public void focusLost(FocusEvent focusEvent) {
                if (inputLogin.getText().equals("")){
                    inputLogin.setForeground(Color.gray);
                    inputLogin.setText("Логин");
                }

            }
        });
        inputLogin.setForeground(Color.gray);
        inputLogin.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                    inputName.requestFocus();
                }
            }
        });
        dlg.add(inputLogin, new GridBagConstraints(1, 1, 2, 1, 0, 0.1, GridBagConstraints.NORTHWEST, GridBagConstraints.WEST, new Insets(28, 8, 0, 56), 0, 0));

        inputName = new JTextField("Имя пользователя");
        inputName.setPreferredSize(new Dimension(180, 22));
        inputName.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent focusEvent) {
                inputName.setForeground(Color.black);
                if (inputName.getText().equals("Имя пользователя")){
                    inputName.setText("");
                }
            }
            @Override
            public void focusLost(FocusEvent focusEvent) {
                if (inputName.getText().equals("")){
                    inputName.setForeground(Color.gray);
                    inputName.setText("Имя пользователя");
                }

            }
        });
        inputName.setForeground(Color.gray);
        inputName.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                    addUser();
                }
            }
        });
        dlg.add(inputName, new GridBagConstraints(1, 2, 2, 1, 0, 0.1, GridBagConstraints.NORTHWEST, GridBagConstraints.WEST, new Insets(18, 8, 0, 56), 0, 0));

        roleList = new JComboBox(usersTableModel.getUserRoles().values().toArray());
        roleList.setPreferredSize(new Dimension(180, 22));
        dlg.add(roleList, new GridBagConstraints(1, 3, 1, 1, 0, 0.1, GridBagConstraints.NORTHWEST, GridBagConstraints.WEST, new Insets(18, 8, 0, 0), 0, 0));

        JButton okButton = new JButton("Добавить");
        okButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                addUser();
            }
        });
        okButton.setPreferredSize(new Dimension(90, 24));
        dlg.add(okButton, new GridBagConstraints(1, 4, 2, 1, 0, 50, GridBagConstraints.NORTHWEST, GridBagConstraints.WEST, new Insets(18, 8, 30, 0), 0, 0));

        JButton cancelButton = new JButton("Отмена");
        cancelButton.setPreferredSize(new Dimension(90, 24));
        dlg.add(cancelButton, new GridBagConstraints(1, 4, 2, 1, 0, 50, GridBagConstraints.NORTHWEST, GridBagConstraints.WEST, new Insets(18, 102, 30, 56), 0, 0));
        cancelButton.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                dlg.dispose();
            }
        });

        dlg.pack();

        Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
        dlg.setLocation(screensize.width / 2 - dlg.getWidth() / 2, screensize.height / 2 - dlg.getHeight() / 2);

        dlg.setVisible(true);

    }

    private void addUser() {
        if (inputLogin.getText().equals("") || inputLogin.getText().equals("Логин")) {
            JOptionPane.showMessageDialog(dlg, "Логин не может быть пустым", "Error", JOptionPane.ERROR_MESSAGE);
            inputLogin.requestFocus();
            return;
        }

        for (FactageUser user : usersTableModel.getData()) {
            if (user.getLogin().equals(inputLogin.getText())) {
                JOptionPane.showMessageDialog(dlg, "Пользователь с таким логином удже существует", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
        }

        try {
            Connection connSQL = MsSQLConnect.ConnectDB("Factage");

            Statement stat = connSQL.createStatement();
            stat.executeUpdate("INSERT users([login], [password], [name], [role_id]) VALUES ('"+inputLogin.getText()+"', '"+FactageUser.md5(inputLogin.getText())+"', '"+inputName.getText()+"', "+Integer.valueOf(roleList.getSelectedIndex()+1)+")");

            stat.close();

            connSQL.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        dlg.dispose();
    }

}
